import numpy as np
import pandas as pd

'''
cat对象
'''
df = pd.read_csv('data/learn_pandas.csv',
     usecols = ['Grade', 'Name', 'Gender', 'Height', 'Weight'])
s = df.Grade.astype('category')

s.resample('10D').mean().head()
'''
时间戳
'''
ts = pd.Timestamp('2020/1/1')
ts = pd.Timestamp('2020-1-1 08:10:30')

pd.to_datetime(['2020-1-1', '2020-1-3', '2020-1-6'])
df = pd.read_csv('data/learn_pandas.csv')
s = pd.to_datetime(df.Test_Date)
# 时间格式化
temp = pd.to_datetime(['2020\\1\\1','2020\\1\\3'],format='%Y\\%m\\%d')
pd.Series(temp).head()
df_date_cols = pd.DataFrame({'year': [2020, 2020],
                             'month': [1, 1],
                             'day': [1, 2],
                             'hour': [10, 20],
                             'minute': [30, 50],
                             'second': [20, 40]})
pd.to_datetime(df_date_cols)
# 生成时间间隔相等的时间序列
pd.date_range('2020-1-1','2020-1-21', freq='10D') # 包含
pd.date_range('2020-1-1','2020-2-28', freq='10D')
pd.date_range('2020-1-1',
              '2020-2-28', periods=6) # 由于结束日期无法取到，freq不为10天

s = pd.Series(np.random.rand(5),
            index=pd.to_datetime([
                '2020-1-%d'%i for i in range(1,10,2)]))
s.head()
s.asfreq('D').head()
s.asfreq('12H').head()

'''
dt 对象
'''
s = pd.Series(pd.date_range('2020-1-1','2020-1-3', freq='D'))
s.dt.date
s.dt.time
s.dt.day
s.dt.daysinmonth
s.dt.dayofweek
s.dt.month_name()
s.dt.day_name()
s.dt.is_year_start # 还可选 is_quarter/month_start
s.dt.is_year_end # 还可选 is_quarter/month_end
s = pd.Series(pd.date_range('2020-1-1 20:35:00',
                            '2020-1-1 22:35:00',
                            freq='45min'))
s.dt.round('1H')
s.dt.ceil('1H')
s.dt.floor('1H')
s = pd.Series(np.random.randint(2,size=366),
              index=pd.date_range(
                      '2020-01-01','2020-12-31'))
idx = pd.Series(s.index).dt
s[(idx.is_month_start|idx.is_month_end).values].head()
s[idx.dayofweek.isin([5,6]).values].head()
# 取出7月
s['2020-07'].head()
s['2020-05':'2020-7-15'].head()
s['2020-05':'2020-7-15'].tail()

'''
时间差
'''
pd.Timestamp('20200102 08:00:00')-pd.Timestamp('20200101 07:35:00')
pd.Timedelta(days=1, minutes=25) # 需要注意加s
pd.Timedelta('1 days 25 minutes') # 字符串生成

s = pd.to_timedelta(df.Time_Record)
pd.timedelta_range('0s', '1000s', freq='6min')
pd.timedelta_range('0s', '1000s', periods=3)

s.dt.seconds.head()
s.dt.total_seconds().head()
pd.to_timedelta(df.Time_Record).dt.round('min').head()

'''
Timedelta的运算
'''
td1 = pd.Timedelta(days=1)
td2 = pd.Timedelta(days=3)
ts = pd.Timestamp('20200101')
td1 * 2
td2 - td1
ts + td1
ts - td1

td1 = pd.timedelta_range(start='1 days', periods=5)
td2 = pd.timedelta_range(start='12 hours',
                         freq='2H',
                         periods=5)
ts = pd.date_range('20200101', '20200105')
td1 * 5
td1 * pd.Series(list(range(5))) # 逐个相乘
td1 + ts # 逐个相加

'''
Offset对象
'''
pd.Timestamp('20200831') + pd.offsets.WeekOfMonth(week=0,weekday=0)
pd.Timestamp('20200907') + pd.offsets.BDay(30)
pd.Timestamp('20200831') - pd.offsets.WeekOfMonth(week=0,weekday=0)
pd.Timestamp('20200907') - pd.offsets.BDay(30)
pd.Timestamp('20200907') + pd.offsets.MonthEnd()
my_filter = pd.offsets.CDay(n=1,weekmask='Wed Fri',holidays=['20200109'])
dr = pd.date_range('20200108', '20200111')
dr.to_series().dt.dayofweek

[i + my_filter for i in dr]


pd.date_range('20200101','20200331', freq='MS') # 月初
pd.date_range('20200101','20200331', freq='M') # 月末
pd.date_range('20200101','20200110', freq='B') # 工作日
pd.date_range('20200101','20200201', freq='W-MON') # 周一
pd.date_range('20200101','20200201',
              freq='WOM-1MON') # 每月第一个周一

pd.date_range('20200101','20200331',
              freq=pd.offsets.MonthBegin())
pd.date_range('20200101','20200331',
              freq=pd.offsets.MonthEnd())
pd.date_range('20200101','20200110', freq=pd.offsets.BDay())
pd.date_range('20200101','20200201',
              freq=pd.offsets.CDay(weekmask='Mon'))
pd.date_range('20200101','20200201',
              freq=pd.offsets.WeekOfMonth(week=0,weekday=0))


'''
滑动窗口
'''
import matplotlib.pyplot as plt
idx = pd.date_range('20200101', '20201231', freq='B')
np.random.seed(2020)
data = np.random.randint(-1,2,len(idx)).cumsum() # 随机游动构造模拟序列
s = pd.Series(data,index=idx)

r = s.rolling('30D')
plt.plot(s)
plt.title('BOLL LINES')
plt.plot(r.mean())
plt.plot(r.mean()+r.std()*2)
plt.plot(r.mean()-r.std()*2)

s.shift(freq='50D').head()

my_series = pd.Series(s.index)
my_series.head()
my_series.diff(1).head()

s.resample('10D').mean().head()
s.resample('10D').apply(lambda x:x.max()-x.min()).head() # 极差

idx = pd.date_range('20200101 8:26:35', '20200101 9:31:58', freq='77s')
data = np.random.randint(-1,2,len(idx)).cumsum()
s = pd.Series(data,index=idx)
s.resample('7min').mean().head()
s.resample('7min', origin='start').mean().head()

s = pd.Series(np.random.randint(2,size=366),
              index=pd.date_range('2020-01-01',
                                  '2020-12-31'))
# z最后一天
s.resample('M').mean().head()
s.resample('MS').mean().head() # 结果一样，但索引不同
